<template>
  <div class="app-container">
    <!--查询条件开始-->
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级名称"
          clearable
          size="small"
          style="width:240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getListForPage">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--查询条件结束-->

    <!--表头按钮开始-->
    <el-row :gutter="10" style="margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除
        </el-button>
      </el-col>
    </el-row>

    <!--表头按钮结束-->

    <!--数据表格开始-->
    <el-table v-loading="loading" border :data="deptTableList" @selection-change="handleSelectionChnage">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="班级名称" align="center" prop="className">
        <template slot-scope="scope">
          <el-button type="text" @click="openDialogTable(scope.row)">{{ scope.row.className }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="班级人数" align="center" prop="classCount"/>
      <el-table-column label="班级状态" align="center" prop="status" :formatter="statusFormatter"/>
      <el-table-column label="负责班主任" align="center" prop="classTeachB"/>
      <el-table-column label="教员" align="center" prop="classTeachJ"/>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--数据表格结束-->

    <!--分页控件开始-->
    <el-pagination
      v-show="total>0"
      :current-page="queryParams.pageNum"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!--分页控件结束-->

<!--    班级学生弹框-->
    <el-dialog :title="title" :visible.sync="dialogTableVisible" :close-on-click-modal="false" v-dialogDrag>
      <el-table :data="studentList">
        <el-table-column property="stuName" label="姓名"></el-table-column>
        <el-table-column property="stuSex" label="性别" >
          <template slot-scope="scope">
            <span v-if="scope.row.stuSex == 0">男</span>
            <span v-if="scope.row.stuSex == 1">女</span>
          </template>
        </el-table-column>
        <el-table-column property="stuAge" label="年龄"></el-table-column>
        <el-table-column property="stuPhone" label="联系电话"></el-table-column>
        <el-table-column property="stuId" label="身份证号码"></el-table-column>
      </el-table>
    </el-dialog>

    <!--添加修改弹出层开始-->
    <el-dialog :title="title" :visible.sync="open" width="500px" center append-to-body :close-on-click-modal="false" v-dialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" clearable size="small"/>
        </el-form-item>

        <el-form-item label="校区老师" prop="campus">
          <el-select v-model="form.campus" placeholder="请选择校区老师" class="right-menu-item hover-effect" @change="selectCampus" style="width: 100%;">
            <el-option
              v-for="d in schoolType"
              :key="d.dictValue"
              :label="d.dictLabel"
              :value="d.dictValue">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="班主任" prop="classTeachB">
          <el-select
            style="width: 100%;"
            v-model="form.teacherB"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择班主任"
          >
            <el-option
              v-for="item in teacherB"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="教员" prop="classTeachJ">
          <el-select
            style="width: 100%;"
            v-model="form.teacherJ"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择教员"
          >
            <el-option
              v-for="item in teacherJ"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              :value="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>

    <!--添加修改弹出层结束-->
  </div>
</template>
<script>
import { listClassForPage, addClass, deleteClassByIds, updateClass, getClassById } from '@/api/system/class'
import { selectAllUser } from '@/api/system/user'
import { getStudentByClassId } from '@/api/system/student'

export default {
  data() {
    return {
      //查询条件
      queryParams: {
        deptName: undefined,
        status: undefined,
        pageNum: 1,
        pageSize: 10
      },
      // 时间
      dateRange: [],
      // 状态数据值集
      statusOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层显示
      open: false,
      // 弹出层标题
      title: '',
      // 遮罩
      loading: false,
      // 表格数据
      deptTableList: [],
      // 表单校验
      rules: {
        className: [
          { required: true, message: '班级名称不能为空', trigger: 'blur' }
        ]
      },
      //表单数据
      form: {},
      //选中的id
      ids: [],
      names:[],
      //数据数量
      total: 0,
      // 班主任
      teacherB: [],
      // 教员
      teacherJ: [],
      // 学生弹出框
      dialogTableVisible:false,
      // 学生数据
      studentList:[],
      // 校区集合
      schoolType:[]
    }
  },
  //钩子
  created() {
    this.getDataByType('sys_normal_disable').then(res => {
      this.statusOptions = res.data
    })
    this.getDataByType('sys_school_type').then(res=>{
      this.schoolType = res.data
    })
    this.getListForPage()
  },
  methods: {
    //查询表格数据
    getListForPage() {
      this.loading = true
      listClassForPage(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
          //获得请求的数据
          this.deptTableList = res.data
          //获得请求的条数
          this.total = res.total
          this.loading = false
        })
    },

    // 打开学生弹框
    openDialogTable(row){
      getStudentByClassId(row.classId).then(res => {
        this.studentList = res.data
        this.title = row.className+' 的学生'
        this.dialogTableVisible = true
      })
    },

    // 选择校区触发
    selectCampus(select){
      this.teacherJ = []
      this.teacherB = []
      selectAllUser(select).then(res => {
        Object.keys(res.data).forEach(index => {
          if (res.data[index].userRank === '2' || res.data[index].userRank === '6' || res.data[index].userRank === '7') {
            this.teacherB.push(res.data[index])
          }
          if (res.data[index].userRank === '3' || res.data[index].userRank === '5') {
            this.teacherJ.push(res.data[index])
          }
        })
      })
    },

    //重置按钮事件
    resetQuery() {
      this.resetForm('queryForm')
      this.dateRange = []
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getListForPage()
    },
    //新增弹出层
    handleAdd() {
      this.reset()
      this.selectCampus()
      this.open = true
      this.title = '添加班级'
    },

    // 修改弹出层
    handleUpdate(row) {
      this.reset()
      this.selectCampus()
      let classId = row.classId === undefined ? this.ids[0] : row.classId
      this.title = '修改班级'
      getClassById(classId).then(res => {
        this.form = res.data
        this.open = true
      })
    },

    //表头删除操作
    handleDelete(row) {
      let classId = row.classId === undefined ? this.ids : row.classId
      let className = row.classId === undefined ? this.names:row.className
      this.$confirm('是否删除 '+className+' 数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteClassByIds(classId).then(res => {
          this.msgSuccess('删除成功')
          this.getListForPage()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },

    //表格多选框选中事件
    handleSelectionChnage(selection) {
      this.ids = selection.map(item => item.classId)
      this.names = selection.map(item => item.className)
      this.single = !(selection.length === 1)
      this.multiple = !(selection.length > 0)
    },

    //翻译状态
    statusFormatter(row) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },

    //当前页大小发生改变触发事件
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getListForPage()
    },

    //当前页改变触发事件
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getListForPage()
    },

    //添加修改提交触发事件
    handleSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          //ture 添加
          this.form.campus = undefined;
          if (this.form.classId === undefined) {
            this.$confirm('请确认是否添加到当前校区下!', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              addClass(this.form).then(res =>{
                this.msgSuccess(res.msg)
                this.open = false
                this.getListForPage()
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消添加'
              });
            });
          } else {
            this.$confirm('请确认是否添加到当前校区下!', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              updateClass(this.form).then(res => {
                this.msgSuccess('修改成功')
                this.open = false
                this.getListForPage()
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消修改'
              });
            });
          }
        }
      })

    },
    //取消触发事件
    cancel() {
      this.open = false
    },
    //添加修改重置表单
    reset() {
      this.form = {
        className: null,
        teacherB: [],
        teacherJ: [],
        status: '0'
      }
      this.resetForm('form')
    }

  }
  , watch: {
    'queryParams.deptName': {
      handler(val, oldVal) {
        this.queryParams.pageNum = 1
        this.getListForPage()
      },
      deep: true
    },
    'queryParams.status': {
      handler(val, oldVal) {
        this.queryParams.pageNum = 1
        this.getListForPage()
      },
      deep: true
    },
    'dateRange': {
      handler(val, oldVal) {
        this.queryParams.pageNum = 1
        this.getListForPage()
      },
      deep: true
    }
  }

}
</script>
